<!doctype html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-model="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<div id="app">
    <p>Ask a yes/no question:<input type="text" v-model="question"></p>
    <p>Answer:{{answer}}</p>
</div>
</body>
<script src="../../vender/vue@2.4.2.js"></script>
<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
<script>
    const getApi=()=>new Promise((resolve,reject)=>{
        setTimeout(()=>{
            if(Math.random()<0.3)return reject('Timeout');
            let answer=Math.random()<0.5;
            resolve({
                answer:answer?'Yes':'No',
                forced:answer
            });
        },Math.random()*1000|0);
    });
    var app=new Vue({
        el:'#app',
        data:{
            question:'',
            answer:'I can not give you a answer until you ask a question!'
        },
        watch:{
            question: function () {
                console.log('question:',this.question);
                this.answer='Waiting for you to stop typing';
                this.getAnswer();
            }
        },
        methods:{
            getAnswer: _.debounce(function () {
                if(-1 == this.question.indexOf('?'))return this.answer='Question usually contain a question mark. :-)';
                this.answer='Thinking...';
                console.log('Answer:',this.answer);
                var vm=this;
                getApi().then(res=>{
                    vm.answer=res.answer;
                    console.info('res:',vm.answer);
                }).catch(err=>{
                    console.error(err);
                    vm.answer='Error! Could not reach the API';
                });
            },500)
        }
    });

</script>
</html>